<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="名称">
          <a-input placeholder="请输入活动名称" v-decorator="['name',  validatorRules.name]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="条件：每满">
          <a-input-number v-decorator="[ 'minCount',  validatorRules.minCount]"/>
          件
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="优惠：赠送">
          <a-input-number v-decorator="[ 'freeCount',  validatorRules.freeCount]"/>
          件
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="单次最多：赠送">
          <a-input-number v-decorator="[ 'limitCount',  validatorRules.limitCount]"/>
          件（0表示不限）
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="开始时间：">
          <a-date-picker format="YYYY-MM-DD HH:mm:ss" :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                         v-decorator="[ 'startTime', validatorRules.startTime]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="截至时间：">
          <a-date-picker format="YYYY-MM-DD HH:mm:ss" :show-time="{ defaultValue: moment('23:59:59', 'HH:mm:ss') }"
                         v-decorator="[ 'endTime', validatorRules.endTime]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="使用类型">
          <j-dict-select-tag v-decorator="['useType', validatorRules.useType]" placeholder="使用类型"
                             @change="handleUseType" :type="'radioButton'" :triggerChange="true" dictCode="useType"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :hidden="this.model.useType!=='1'"
          label="关联分类">
          <a-button type="primary" icon="search" @click="handleShowCategory">选择分类</a-button>
          <a-select
            mode="multiple"
            :placeholder="'请选择分类'"
            v-model="selectCategoryValue"
            :options="selectCategoryOptions"
            allowClear
            :disabled="false"
            :open="false"
            style="width: 100%;"
            @click.native="visible=true"
          />
          <select-product-category-modal ref="SelectProductCategoryModal" @selectFinished="selectCategoryOK"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :hidden="this.model.useType!=='2'"
          label="关联商品">
          <a-button type="primary" icon="search" @click="handleShowProduct">选择商品</a-button>
          <a-select
            mode="multiple"
            :placeholder="'请选择商品'"
            v-model="selectProductValue"
            :options="selectProductOptions"
            allowClear
            :disabled="false"
            :open="false"
            style="width: 100%;"
            @click.native="visible=true"
          />
          <select-product-modal ref="SelectProductModal" @selectFinished="selectProductOK"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="参与经销商">
          <j-dict-select-tag v-decorator="['storeType', validatorRules.storeType]" placeholder="参与经销商"
                             @change="handleStore" :type="'radioButton'" :triggerChange="true"
                             dictCode="giftStoreType"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :hidden="this.model.storeType!=='1'"
          label="关联分组">
          <a-button type="primary" icon="search" @click="handleShowGroup">选择分组</a-button>
          <a-select
            mode="multiple"
            :placeholder="'请选择分组'"
            v-model="selectGroupValue"
            :options="selectGroupOptions"
            allowClear
            :disabled="false"
            :open="false"
            style="width: 100%;"
            @click.native="visible=true"
          />
          <select-store-group-modal ref="SelectStoreGroupModal" @selectFinished="selectStoreGroupOK"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :hidden="this.model.storeType!=='2'"
          label="关联经销商">
          <a-button type="primary" icon="search" @click="handleShowStore">选择经销商</a-button>
          <a-select
            mode="multiple"
            :placeholder="'请选择经销商'"
            v-model="selectStoreValue"
            :options="selectStoreOptions"
            allowClear
            :disabled="false"
            :open="false"
            style="width: 100%;"
            @click.native="visible=true"
          />
          <select-store-modalJX ref="SelectStoreModalJX" @selectFinished="selectStoreOK"/>
        </a-form-item>


        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="备注">
          <a-input placeholder="请输入备注" v-decorator="['note', {}]"/>
        </a-form-item>

      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import {httpAction, getAction} from '@/api/manage'
import pick from 'lodash.pick'
import moment from "moment"
import JDate from '@/components/jeecg/JDate'
import JEditableTable from '@/components/jeecg/JEditableTable'
import {FormTypes, VALIDATE_NO_PASSED, getRefPromise, validateFormAndTables} from '@/utils/JEditableTableUtil'
import SelectProductModal from '../../pms/modules/SelectProductModal'
import SelectProductCategoryModal from '../../pms/modules/SelectProductCategoryModal'
import SelectStoreGroupModal from '../../stm/modules/SelectStoreGroupModal'
import JMultiSelectTag from '@/components/dict/JMultiSelectTag'
import SelectStoreModalJX from '../../stm/modules/SelectStoreModalJX'

export default {
  name: "SmsGiftInfoModal",
  components: {
    JDate,
    JEditableTable,
    SelectProductModal,
    SelectProductCategoryModal,
    SelectStoreGroupModal,
    JMultiSelectTag,
    SelectStoreModalJX
  },
  data() {
    return {
      title: "操作",
      visible: false,
      model: {},
      selectCategoryValue: [],
      selectCategoryOptions: [],
      selectProductValue: [],
      selectProductOptions: [],
      selectGroupValue: [],
      selectGroupOptions: [],
      selectStoreValue: [],
      selectStoreOptions: [],
      labelCol: {
        xs: {span: 24},
        sm: {span: 5},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },

      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        name: {rules: [{required: true, message: '名称不可为空!'}]},
        minCount: {rules: [{required: true, message: '必填字段不能为空!'}]},
        freeCount: {rules: [{required: true, message: '必填字段不能为空!'}]},
        limitCount: {rules: [{required: true, message: '必填字段不能为空!'}]},
        startTime: {rules: [{required: true, message: '请选择活动开始时间!'}]},
        endTime: {rules: [{required: true, message: '请选择活动截止时间!'}]},
        useType: {rules: [{required: true, message: '请选择使用类型!'}]},
        storeType: {rules: [{required: true, message: '请选择参与经销商类型!'}]},
      },
      url: {
        add: "/sms/smsGiftInfo/add",
        edit: "/sms/smsGiftInfo/edit",
        queryCategoryRelationById: "/sms/smsGiftInfo/queryCategoryRelationById",
        queryProductRelationById: "/sms/smsGiftInfo/queryProductRelationById",
        queryStoreRelationById: "/sms/smsGiftInfo/queryStoreRelationById",
        queryStoreGroupRelationById: "/sms/smsGiftInfo/queryStoreGroupRelationById",
      },
    }
  },
  created() {
  },
  methods: {
    moment,
    add() {
      this.edit({});
    },
    edit(record) {
      this.form.resetFields();
      this.selectCategoryValue = [];
      this.selectCategoryOptions = [];
      this.selectProductValue = [];
      this.selectProductOptions = [];
      this.selectStoreValue = [];
      this.selectStoreOptions = [];
      this.selectGroupValue = [];
      this.selectGroupOptions = [];
      this.model = Object.assign({}, record);
      this.visible = true;
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'name', 'minCount', 'freeCount', 'limitCount', 'startTime', 'endTime', 'useType', 'storeType'))
        //时间格式化
        this.form.setFieldsValue({startTime: this.model.startTime ? moment(this.model.startTime) : null})
        this.form.setFieldsValue({endTime: this.model.endTime ? moment(this.model.endTime) : null})
      });

      if (this.model.useType === null || this.model.useType === '' || this.model.useType === undefined) {
        this.model.useType = '';
      } else {
        if (this.model.id !== null && this.model.id !== '' && this.model.id !== undefined) {
          if (this.model.useType === 1) {
            this.getCategory();
          } else if (this.model.useType === 2) {
            this.getProduct();
          }
        }
        this.model.useType = this.model.useType.toString();
      }
      if (this.model.storeType === null || this.model.storeType === '' || this.model.storeType === undefined) {
        this.model.storeType = '';
      } else {
        if (this.model.id !== null && this.model.id !== '' && this.model.id !== undefined) {
          if (this.model.storeType === 1) {
            this.getStoreCategory();
          } else if (this.model.storeType === 2) {
            this.getStore();
          }
        }
        this.model.storeType = this.model.storeType.toString();
      }

    },
    close() {
      this.$emit('close');
      this.visible = false;
    },
    handleOk() {
      const that = this;
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (!this.model.id) {
            httpurl += this.url.add;
            method = 'post';
          } else {
            httpurl += this.url.edit;
            method = 'put';
          }
          let formData = Object.assign(this.model, values);
          //时间格式化
          formData.startTime = formData.startTime ? formData.startTime.format('YYYY-MM-DD HH:mm:ss') : null;
          formData.endTime = formData.endTime ? formData.endTime.format('YYYY-MM-DD HH:mm:ss') : null;
          formData.categoryList = this.selectCategoryValue
          formData.productList = this.selectProductValue
          formData.storeGroupList = this.selectGroupValue
          formData.storeList = this.selectStoreValue

          console.log(formData)
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.$emit('ok');
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
            that.close();
          })


        }
      })
    },
    handleCancel() {
      this.close()
    },
    handleUseType(e) {
      this.model.useType = e;
    },
    handleStore(e) {
      this.model.storeType = e;
    },
    selectCategoryOK(categoryData) {
      this.selectCategoryOptions = categoryData.map(data => ({label: data['name'], value: data['id']}));
      this.selectCategoryValue = categoryData.map(data => data['id']);
      console.log('selectCategoryOptions => ' + this.selectCategoryOptions);
      console.log('selectCategoryValue => ' + this.selectCategoryValue);
    },
    selectProductOK(productData) {
      this.selectProductOptions = productData.map(data => ({label: data['name'], value: data['id']}));
      this.selectProductValue = productData.map(data => data['id']);
    },
    selectStoreGroupOK(groupData) {
      this.selectGroupOptions = groupData.map(data => ({label: data['name'], value: data['id']}));
      this.selectGroupValue = groupData.map(data => data['id']);
    },
    selectStoreOK(storeData) {
      console.log(storeData)
      this.selectStoreOptions = storeData.map(data => ({label: data['name'], value: data['storeId']}));
      this.selectStoreValue = storeData.map(data => data['storeId']);
    },
    handleShowCategory: function () {
      this.$refs.SelectProductCategoryModal.add();
      this.$refs.SelectProductCategoryModal.title = "选择分类";
    },
    handleShowGroup: function () {
      this.$refs.SelectStoreGroupModal.add();
      this.$refs.SelectStoreGroupModal.title = "选择分组";
    },
    handleShowProduct: function () {
      this.$refs.SelectProductModal.add();
      this.$refs.SelectProductModal.title = "选择商品";
    },
    handleShowStore: function () {
      this.$refs.SelectStoreModalJX.brandCategory = "1";
      this.$refs.SelectStoreModalJX.add();
      this.$refs.SelectStoreModalJX.title = "选择经销商";
    },
    getCategory() {
      getAction(this.url.queryCategoryRelationById, {id: this.model.id}).then(res => {
        if (res.success) {
          console.log('CategoryData => ' + res.result);
          this.selectCategoryOptions = res.result.map(data => ({
            label: data['productCategoryName'],
            value: data['productCategoryId']
          }));
          this.selectCategoryValue = res.result.map(data => data['productCategoryId']);
        } else {
          console.log(res.message);
        }
      });
    },
    getProduct() {
      getAction(this.url.queryProductRelationById, {id: this.model.id}).then(res => {
        if (res.success) {
          console.log('ProductData => ' + res.result);
          this.selectProductOptions = res.result.map(data => ({label: data['productName'], value: data['productId']}));
          this.selectProductValue = res.result.map(data => data['productId']);
        } else {
          console.log(res.message);
        }
      });
    },
    getStore() {
      getAction(this.url.queryStoreRelationById, {id: this.model.id}).then(res => {
        if (res.success) {
          console.log('ProductData => ' + res.result);
          this.selectStoreOptions = res.result.map(data => ({label: data['storeName'], value: data['storeId']}));
          this.selectStoreValue = res.result.map(data => data['storeId']);
        } else {
          console.log(res.message);
        }
      });
    },
    getStoreCategory(){
      getAction(this.url.queryStoreGroupRelationById, {id: this.model.id}).then(res => {
        if (res.success) {
          console.log('selectGroupOptions => ' + res.result);
          this.selectGroupOptions = res.result.map(data => ({
            label: data['storeGroupName'],
            value: data['storeGroupId']
          }));
          this.selectGroupValue = res.result.map(data => data['storeGroupId']);
        } else {
          console.log(res.message);
        }
      });
    }
  }
}
</script>

<style lang="less" scoped>

</style>